package MapBase.logic.control.xml
{
	import MapBase.logic.untils.MapConfig;
	
	import com.friendsofed.isometric.IsoObject;
	import com.friendsofed.isometric.IsoUtils;
	import com.friendsofed.isometric.IsoWorld;
	import com.friendsofed.isometric.Point3D;
	
	import flash.geom.Point;

	public class EntityFloorXML
	{
		private var _entityXML:XML;
		private var _world:IsoWorld;
		private var _tileList:Object;
		
		private var _type : int;
		
		public function EntityFloorXML(world:IsoWorld,tileList:Object,type:int)
		{
			_world = world;
			_tileList = tileList;
			_type = type;
		}
		
		public function save():void
		{
			create();
			var file:MapConfig  = new MapConfig;
			file.saveConfig(_entityXML,"buildFloor");
		}
		
		public function create():void
		{
			var floors : Object = new Object;
			for each(var tle : Object in _tileList)
			{
				if(tle.hasOwnProperty("ownId"))
				{
					if(!floors.hasOwnProperty(tle["ownId"]))
					{
						floors[tle["ownId"]] = new Array;
					}
					
					var isoObj : IsoObject ;
					
					for(var i:int=0;i<_world.objects.length;i++)
					{
						isoObj=_world.objects[i];
						if(isoObj.id == tle["ownId"])
						{
							break;
						}
					}
					
					var p3:Point3D ;
					
					if(_type == 1)
					{
						p3 = IsoUtils.screenToIso( new Point( Number( tle["tile"].x ),Number( tle["tile"].y) ) );
						
						floors[tle["ownId"]].push(p3.x - isoObj.x);
						floors[tle["ownId"]].push(p3.z - isoObj.z);
					}
					else if(_type == 2)
					{
						p3 = IsoUtils.screenToIso( new Point( Number( tle["tile"].x ),Number( tle["tile"].y) ) );
						
						floors[tle["ownId"]].push(p3.x - isoObj.x);
						floors[tle["ownId"]].push(p3.z - isoObj.z);
					}
					else if(_type == 3)
					{
						var p:Point = new Point( Number( tle["tile"].x ),Number( tle["tile"].y) ) ;
						//trace("p.x:", p.x, 
							  //"p.y:",p.y,
							  //"isoObj.x:", isoObj.x,
							  //"isoObj.z", isoObj.z,
							  //"p.x - isoObj.x:",p.x - isoObj.x,
							  //"ip.y - isoObj.z:",p.y - isoObj.z);
						var ps : Point = IsoUtils.isoToScreen(isoObj.position);
						floors[tle["ownId"]].push(p.x - ps.x);
						floors[tle["ownId"]].push(p.y - ps.y);
					}
				}
			}
			
			_entityXML = <buildFloor>
						</buildFloor>;
			
			for (var id:String in floors)
			{
				var appendXml : XML = <item/>;
				appendXml.@id = id;
				appendXml.@floor = floors[id];
				_entityXML.appendChild(appendXml);
			}
		}
	}
}